package com.company.project.service.impl;

import com.company.project.dao.VtProductMapper;
import com.company.project.model.VO.ProductVO;
import com.company.project.model.VtProduct;
import com.company.project.service.VtProductService;
import com.company.project.core.AbstractService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;


/**
 * Created by CodeGenerator on 2023/10/20.
 */
@Service
@Transactional
public class VtProductServiceImpl extends AbstractService<VtProduct> implements VtProductService {
    @Resource
    private VtProductMapper vtProductMapper;

    @Override
    public List<ProductVO> findProductMenu() {
        //数据查询
        List<VtProduct> tempList = vtProductMapper.selectAll();
        List<ProductVO> list = new ArrayList<>();
        for (VtProduct product: tempList) {
            ProductVO productVO = new ProductVO();
            productVO.setId(product.getId());
            productVO.setName(product.getName());
            productVO.setListorder(product.getListorder());
            productVO.setModulus(product.getModulus());
            productVO.setParentid(product.getParentid());
            productVO.setUnitprice(product.getUnitprice());
            productVO.setChildren(new ArrayList<>());
            productVO.setValue(product.getId());
            productVO.setText(product.getName());
            list.add(productVO);
        }
        //新建一个用于接收数据的list
        List<ProductVO> resultList = new ArrayList<>();
        for (ProductVO product : list) {
            if (product.getParentid() == 0) {
                //调用方法给子类添加数据
                resultList.add(getMenuTree(product, list));
            }
        }
        return resultList;
    }

        private ProductVO getMenuTree(ProductVO result, List<ProductVO> list) {
        for (ProductVO product : list) {
            if (product.getParentid().equals(result.getId())) {
                if (result.getChildren() == null) {
                    result.setChildren(new ArrayList<>());
                }
                // 递归调用
                ProductVO productVO = getMenuTree(product, list);
                result.getChildren().add(productVO);
            }
        }
        return result;
    }

}
